package org.dydl.service.system.impl;

import java.util.Date;
import java.util.List;
import java.util.UUID;

import org.apache.commons.lang.StringUtils;
import org.dydl.common.dto.ResponseData;
import org.dydl.common.dto.ResponseMessage;
import org.dydl.dao.system.repository.ILossRepository;
import org.dydl.dao.system.repository.LossDetailRepository;
import org.dydl.model.system.Area;
import org.dydl.model.system.Loss;
import org.dydl.model.system.Lossdetail;
import org.dydl.service.system.LossService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

@Service
public class LossServiceImpl implements LossService {
	
	@Autowired
	private ILossRepository iLossRepository;
	@Autowired
	private LossDetailRepository lossDetailRepository;
	
	private  ResponseMessage res = new ResponseMessage();
	
	/**
	 * 查询耗损关系列表
	 * @param page
	 * @param rows
	 * @param name
	 * @return
	 */
	@Override
	public ResponseMessage list(int page, int rows, String name){
  		Pageable pageable = new PageRequest(page - 1, rows);
		Page<Area> pageList = null;
		if (StringUtils.isNotBlank(name)) {
			pageList = iLossRepository.getListLike(String.format("%s%s%s", "%", StringUtils.trim(name), "%"),pageable);
		} else {
			pageList = iLossRepository.getList(pageable);
		}
		return new ResponseMessage(true, new ResponseData<Area>(page, pageList.getTotalPages(),
				((int) pageList.getTotalElements()), pageList.getContent()));
	}
	
	/**
	 * 保存
	 * @param loss
	 * @return
	 */
	@Override
	public ResponseMessage save(Area loss) {
		
		return new ResponseMessage(true, iLossRepository.save(loss));
	}

	/**
	 * 删除
	 * @param id
	 */
	@Override
	public void delete(int id) {
		iLossRepository.delete(id);
	}

	/**
	 * 根据uuid查询耗损关系
	 * @param uuid
	 * @return
	 */
	@Override
	public Loss findByUuid(String uuid) {
		// TODO Auto-generated method stub
		Loss loss = iLossRepository.findByUuid(uuid);
		return loss;
	}

	/**
	 * 保存所需物料列表
	 * @param Lossdetail
	 */
	@Override
	public void saveMaterial(List<Lossdetail> lossdetail) {
			lossDetailRepository.save(lossdetail);
	}

	/**
	 * 根据 bom号查询bom单表头信息
	 * @param bomNo bom 号
	 * @return
	 */
	@SuppressWarnings("finally")
	@Override
	public ResponseMessage getBomBybomNo(String bomNo) {
		try {
			Loss loss = iLossRepository.finBomByBomNo(bomNo);
			res.setSuccess(true);
			res.setData(loss);
		}catch (Exception e){
			res.setSuccess(false);
			res.setMsg(e.getMessage());
		}finally {
			return res;
		}
	}

	/**
	 * 根据bom号查询bom单所需物料
	 * @param bomNo
	 * @return
	 */
	@Override
	public List<Lossdetail> findByBomNo(String bomNo) {
		
		List<Lossdetail> list = lossDetailRepository.findByBomNo(bomNo);
		
		return list;
	}
}
